package com.github.binarywang.demo.wx.cp.utils;

import java.io.*;

/**
 * created by lanxinghua@2dfire.com on 2020/2/14
 * 为了方便用文件当缓存，保存suiteAccessToken
 */
public class CacheUtil {
    private static final String filePath = "tokenCached";
    private static final String keyValueSplit = "->";

    public static final String suiteAccessToken_key = "suiteAccessToken";

    public static void main(String[] args) {
        put("suiteAccessToken", System.currentTimeMillis() + ":" + "xxxx");
        System.out.println(get("suiteAccessToken"));
    }


    public static void put(String key, String value){
        try {
            File file = new File(filePath);
            if (!file.exists()){
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(key + keyValueSplit + value);
            bw.flush();
            bw.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static String get(String key){
        final String[] resultValue = {null};
        try {
            File file = new File(filePath);
            if (!file.exists()){
                file.createNewFile();
            }
            FileReader fr = new FileReader(file);
            BufferedReader bf = new BufferedReader(fr);
            bf.lines().forEach(r -> {
                String readKey =   r.split(keyValueSplit)[0];
                String readValue =   r.split(keyValueSplit)[1];
                if (key.equals(readKey)){
                    resultValue[0] = readValue;
                    return;
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultValue[0];
    }
}
